import 'dart:async';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

/// 建表语句
var contactTable =
    'create table contact(uid int primary key not null, username text not null default "", nick char(10), sex char(1), avatar text, remark text);';
var messageTable = 'create table message();';

class DatabaseHelper {
  static final DatabaseHelper _instance = new DatabaseHelper.internal();

  factory DatabaseHelper() => _instance;

  static Database _db;

  DatabaseHelper.internal();

  Future<Database> get db async {
    if (_db != null) {
      return _db;
    }
    _db = await initDb();

    return _db;
  }

  initDb() async {
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'gobelieve.db');

    var db = await openDatabase(path, version: 1, onCreate: _onCreate);
    return db;
  }

  // 初次打开应用走这里创建表
  void _onCreate(Database db, int newVersion) async {
    await db.execute(contactTable);
    await db.execute(messageTable);
  }
}
